/**
 * SearchConfig.java	1.0 2007 五月 29 14:30:17,创建
 */

package org.in4j.search;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.in4j.search.index.IndexSource;

/**
 *
 * @author 杨帆
 * @version 1.0 2007 五月 29 14:30:17,创建
 */
public class SearchConfig
{
	@SuppressWarnings("unused")
	private static final Log log = LogFactory.getLog(SearchConfig.class);

	private IndexSource[] indexSources;

	public void init(InputStream inputStream)
	{
		try
		{
			initInternal(inputStream);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException("读取搜索配置文件失败,请检查是否正确.");
		}
	}

	private void initInternal(InputStream inputStream) throws Exception
	{
		SAXReader reader = new SAXReader();
		Document doc = reader.read(inputStream);
		Element root = doc.getRootElement();
		List<IndexSource> list = new ArrayList<IndexSource>();
		for(Iterator<Element> iter = root.elementIterator("index-source"); iter.hasNext(); )
		{
			Element element = iter.next();
			String className = element.attributeValue("class");
			IndexSource indexSource = (IndexSource)Class.forName(className).newInstance();
			indexSource.init(element);
			list.add(indexSource);
		}
		this.indexSources = list.toArray(new IndexSource[0]);
	}

	public void init(String configFile)
	{
		this.init(getClass().getResourceAsStream(configFile));
	}

	public IndexSource[] getIndexSources()
	{
		return this.indexSources;
	}
}
